<?php

namespace Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Admin\Form\Product\FormAddProduct;
use Admin\Form\Product\FormAddCategory;
use Library\ResizeImage;
use Admin\Form\Product\FilterAddProduct;
use Admin\Form\Product\FilterAddCategory;
use Admin\Form\Product\FormAddMaker;
use Admin\Form\Product\FilterAddMaker;

class ProductController extends AbstractActionController {

    private $objView;
    private $productModel;

    public function __construct() {
        $this->objView = new ViewModel();
    }

    public function onDispatch(\Zend\Mvc\MvcEvent $e) {
        $this->layout('admin/layout');
        $session = new \Zend\Session\Container('user');
        $userName = $session->offsetGet('name');
        if (isset($userName) === false) {
            return $this->redirect()->toRoute('user-admin');
        } else {
            $this->objView->setVariable('user', $userName);
        }
        return parent::onDispatch($e);
    }

    public function listProductAction() {

        $config = $this->getServiceLocator()->get('config');

        $productType = $config['product_type'];

        $aryConditions = array();

        $currentPage = $this->params()->fromRoute('page_param');

        $categoryId = $this->params()->fromRoute('cat_id');

        $categoryFilter = $this->params()->fromRoute('cat_filter');

        if (!$currentPage) {
            $currentPage = 1;
        }

        if (!$categoryId) {
            $categoryId = 'all';
        }

        if (!$categoryFilter) {
            $categoryFilter = 'category';
        }

        $aryConditions['current_page'] = $currentPage;

        $aryConditions['category_id'] = $categoryId;

        $aryConditions['category_filter'] = $categoryFilter;
        
        $aryConditions['record_per_page'] = $config['product_limit']['product_list'];

        $aryProduct = $this->getProductModule()->getListProduct($aryConditions);

        $this->objView->setVariables($aryConditions);

        $this->objView->setVariable('productType', $productType);

        $this->objView->setVariable('aryProduct', $aryProduct);

        $this->objView->setTemplate('admin/product/list-product');

        return $this->objView;
    }

    public function addProductAction() {

        $config = $this->getServiceLocator()->get('config');

        $productTypeOption = $config['product_type'];

        $productForm = new FormAddProduct($this->getProductModule());

        $request = $this->getRequest();

        if ($request->isPost()) {

            $files = $request->getFiles()->toArray();

            $posts = $request->getPost()->toArray();

            $data = array_merge_recursive($posts, $files);

            $productForm->setInputFilter(new FilterAddProduct($data['action_type']));

            $productForm->setData($data);

            if ($productForm->isValid()) {

                if (isset($files['product_image'])) {

                    $adapter = new \Zend\File\Transfer\Adapter\Http();

                    $adapter->setDestination($config['images_upload_dir']['large_dir']);

                    if ($adapter->receive()) {

                        $this->resizeImage($files['product_image'], $config);
                    }
                }
                $aryData = $productForm->getData();

                $result = $this->getProductModule()->saveProduct($aryData);

                if ($result) {

                    $this->redirect()->toRoute('product-admin');
                }
            }
        }
        $this->objView->setVariable('productTypeOption', $productTypeOption);

        $this->objView->setVariable('productForm', $productForm);

        $this->objView->setTemplate('admin/product/add-product');

        return $this->objView;
    }

    public function resizeImage($files, $config) {
        $largeDir = $config['images_upload_dir']['large_dir'];
        $medium = $config['images_upload_dir']['medium_dir'];
        $thumDir = $config['images_upload_dir']['thumb_dir'];
        copy($largeDir . $files['name'], $thumDir . $files['name']);
        copy($largeDir . $files['name'], $medium . $files['name']);
        $resize = new ResizeImage();
        //for large image
        $resize->setImage($largeDir . $files['name']);
        $resize->setNewSize($config['image_size']['large_size']);
        $resize->save();
        //for medium image
        $resize->setImage($medium . $files['name']);
        $resize->setNewSize($config['image_size']['medium_size']);
        $resize->save();
        //for thumb image
        $resize->setImage($thumDir . $files['name']);
        $resize->setNewSize($config['image_size']['thumb_size']);
        $resize->save();
    }

    public function editProductAction() {

        $productId = $this->params()->fromRoute('param');

        $objProduct = $this->getProductModule()->getProductById($productId);

        $config = $this->getServiceLocator()->get('config');

        $productTypeOption = $config['product_type'];

        $productForm = new FormAddProduct($this->getProductModule());

        $productForm->get('save_product')->setAttribute('value', 'Cập nhật');

        $productForm->get('action_type')->setAttribute('value', 'edit');

        $productForm->bind($objProduct);

        $this->objView->setVariable('productTypeOption', $productTypeOption);

        $this->objView->setVariable('productForm', $productForm);

        $this->objView->setTemplate('admin/product/add-product');

        return $this->objView;
    }

    public function deleteProductAction() {

        $productId = $this->params()->fromRoute('param');

        $result = $this->getProductModule()->deleteProduct($productId);

        if ($result) {
            $this->redirect()->toRoute('product-admin');
        }
    }

    public function listCategoryAction() {
        $aryCategory = $this->getProductModule()->getListCategory();
        $this->objView->setVariable('aryCategory', $aryCategory);
        $this->objView->setTemplate('admin/product/list-category');
        return $this->objView;
    }

    public function addCategoryAction() {

        $config = $this->getServiceLocator()->get('config');

        $formCategory = new FormAddCategory($this->getProductModule());

        $request = $this->getRequest();

        if ($request->isPost()) {

            $files = $request->getFiles()->toArray();

            $post = $request->getPost()->toArray();

            $data = array_merge_recursive($post, $files);

            $formCategory->setInputFilter(new FilterAddCategory($data['action_type']));

            $formCategory->setData($data);

            if ($formCategory->isValid()) {

                if (isset($files['category_image'])) {

                    $adapter = new \Zend\File\Transfer\Adapter\Http();

                    $adapter->setDestination($config['images_upload_dir']['large_dir']);

                    if ($adapter->receive()) {

                        $this->resizeImage($files['category_image'], $config);
                    }
                }
                $aryData = $formCategory->getData();

                $result = $this->getProductModule()->saveCategory($aryData);

                if ($result) {

                    $this->redirect()->toRoute('product-admin/doaction', array(
                        'controller' => 'product-admin-controller',
                        'action' => 'list-category'
                    ));
                }
            }
        }
        $this->objView->setVariable('formCategory', $formCategory);

        $this->objView->setTemplate('admin/product/add-category');

        return $this->objView;
    }

    public function editCategoryAction() {

        $categoryId = $this->params()->fromRoute('param');

        $objCategory = $this->getProductModule()->getCategoryById($categoryId);

        $aryMakerChecked = $this->getProductModule()->getMakerByCategoryId($categoryId);

        $formCategory = new FormAddCategory($this->getProductModule());

        $formCategory->get('action_type')->setAttribute('value', 'edit');

        $formCategory->get('category_submit')->setAttribute('value', 'Cập nhật');

        $formCategory->get('relation_maker_id')->setChecked(true);

        $formCategory->get('relation_maker_id')->setValue($aryMakerChecked);

        $formCategory->get('relation_maker_id')->setCheckedValue($aryMakerChecked);

        $formCategory->bind($objCategory);

        $this->objView->setVariable('formCategory', $formCategory);

        $this->objView->setTemplate('admin/product/add-category');

        return $this->objView;
    }

    public function deleteCategoryAction() {
        $categoryId = $this->params()->fromRoute('param');
        $result = $this->getProductModule()->deleteCategory($categoryId);
        if ($result) {
            $this->redirect()->toRoute('product-admin/doaction', array(
                'controller' => 'product-admin-controller',
                'action' => 'list-category'
            ));
        }
    }

    public function listMakerAction() {

        $aryMaker = $this->getProductModule()->getProductMaker();

        $this->objView->setVariable('aryMaker', $aryMaker);

        $this->objView->setTemplate('admin/product/list-maker');

        return $this->objView;
    }

    public function addMakerAction() {

        $formAddMaker = new FormAddMaker();

        $request = $this->getRequest();

        if ($request->isPost()) {

            $formAddMaker->setInputFilter(new FilterAddMaker());

            $formAddMaker->setData($request->getPost()->toArray());

            if ($formAddMaker->isValid()) {

                $aryData = $formAddMaker->getData();

                $result = $this->getProductModule()->saveMaker($aryData);

                if ($result) {
                    $this->redirect()->toRoute('product-admin/doaction', array('action' => 'list-maker'));
                }
            }
        }

        $this->objView->setVariable('formAddMaker', $formAddMaker);

        $this->objView->setTemplate('admin/product/add-maker');

        return $this->objView;
    }

    public function editMakerAction() {

        $makerId = $this->params()->fromRoute('param');

        $objMaker = $this->getProductModule()->getMakerById($makerId);

        $formAddMaker = new FormAddMaker();

        $formAddMaker->get('action_type')->setAttribute('value', 'edit');

        $formAddMaker->get('save_maker')->setAttribute('value', 'Cập nhật');

        $formAddMaker->bind($objMaker);

        $this->objView->setVariable('formAddMaker', $formAddMaker);

        $this->objView->setTemplate('admin/product/add-maker');

        return $this->objView;
    }

    public function deleteMakerAction() {

        $makerId = $this->params()->fromRoute('param');

        $result = $this->getProductModule()->deleteMaker($makerId);

        if ($result) {
            $this->redirect()->toRoute('product-admin/doaction', array('action' => 'list-maker'));
        }
    }

    public function getProductModule() {
        if (!$this->productModel) {
            $this->productModel = $this->getServiceLocator()->get('ProductAminModel');
        }
        return $this->productModel;
    }

}
